package com.car.frame.baidu.geocoding.api;

import java.util.Map;

import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;

import com.car.frame.baidu.geocoding.api.method.Wgs2Gcj;
import com.czr.xml.XmlUtils;

/**
 * 百度坐标工具
 * 
 * @author chenzhirong
 *
 */
public class GeocodingAPI {

	static String ak = "USEWLm7Q0OrPtY86kp0paVtp";

	private static final Logger log = Logger.getLogger(GeocodingAPI.class);

	/**
	 * 返回的数据格式 xml json
	 */
	private String output = "xml";

	public static void main(String[] args) {
		Gps gps = du2ejz("27.5702433","112.5647190");
		GeocodingAPI geocodingAPI = new GeocodingAPI();
		geocodingAPI.getPath(gps.getWgLat()+","+gps.getWgLon(), coordtype.wgs84ll);
//		geocodingAPI.getPath("27.912690,112.943105", coordtype.wgs84ll);
//		geocodingAPI.getPath("27.912690,112.943105", coordtype.gcj02ll);

	}

	/**
	 * 根据坐标查询详细地址
	 * 
	 * @param zb
	 * @param coordtype
	 */
	public String getPath(String zb, String coordtype) {
		String str = HttpRequest.sendPost(String.format(
				"http://api.map.baidu.com/geocoder/v2/?callback=renderReverse&location=%s&output=%s&pois=0&ak=%s&coordtype=%s",
				zb, output, ak, coordtype), "");
		log.info(str);

		Document doc = null;
		try {
			if(str != null && !"".equals(str)){
				doc = DocumentHelper.parseText(str);
			}else{
				return null;
			}
		} catch (DocumentException e) {
			e.printStackTrace();
		}
		Map<String, Object> map = XmlUtils.Dom2Map(doc);
		Map<String, String> MsgContentMap = (Map<String, String>) map.get("result");
		String path = MsgContentMap.get("formatted_address");
		String sematic_description = MsgContentMap.get("sematic_description");
		return path+sematic_description;
	}

	/**
	 * 将json格式封装的简单实体类型数据转换成简单类型的javabean
	 * 
	 * @return
	 */
	private static void JSON2SimpleBean(String jsonStr) {
		// return JSONObject.toBean(jsonBean, SimpleUser.class);
	}
	
	
	/**
	 * //分秒 转 二进
	 * @param lat
	 * @param lng
	 * @return
	 */
	public static Gps du2ejz(String lat,String lng){
		double du = Double.valueOf(lat.substring(0, 2));
		double mm = Double.valueOf(lat.substring(3, 5));
		double ss = Double.valueOf(lat.substring(5, 7)+"."+lat.substring(7, 10));
		lat = String.valueOf(du+mm/60+ss/3600);
		if(lat.length() > 9){
			lat = lat.substring(0, 9);
		}
		System.out.println(lat);
		
		double lng_du = Double.valueOf(lng.substring(0, 3));
		double lng_mm = Double.valueOf(lng.substring(4, 6));
		double lng_ss = Double.valueOf(lng.substring(6, 8)+"."+lng.substring(8, 11));
		lng = String.valueOf(lng_du+lng_mm/60+lng_ss/3600);
		if(lng.length()> 10){
			lng = lng.substring(0, 10);
		}
		System.out.println(lng);
		Gps gps = new Gps(Double.valueOf(lat),Double.valueOf(lng));
		System.out.println(gps);
		return gps;
	}

}
